package client.ui.view.module;

import client.UserState;
import client.assets.Icons;
import client.control.Controller;
import client.control.ResponseEntity;
import client.entity.Message;
import client.entity.User;
import client.ui.component.layout.VFlowLayout;
import client.ui.theme.ThisFont;
import client.ui.util.MaterialBorder;
import client.ui.util.MaterialColors;
import client.util.ImageUtil;
import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
  * @Description 一条聊天信息
  * @author 孔明浩
  * @Date 2020/3/31
  */
public class ChatRecord extends JPanel {
    //建立一级缓存,图像和用户名
    private final static Map<Integer, ImageIcon> headImages = new HashMap<>();
    private final static Map<Integer, String> names = new HashMap<>();
    //约束图片加载线程
    private static Executor fixedThreadPool = Executors.newFixedThreadPool(2);
    private boolean self = true;
    private boolean showDate = true;
    private String formattedDate = "";
    private String username = "";
    private Message message;
    /**
      * @Description
      * @param self 是否是自己的消息
      * @author 孔明浩
      * @Date 2020/3/31
      */
    public ChatRecord(boolean self){
        super();
        this.self = self;
        initial();
    }

    /**
      * @Description
      * @param message 消息内容
      * @param username 发送消息的人的用户名
      * @author 孔明浩
      * @Date 2020/4/12
      */
    public ChatRecord(boolean self, Message message, String username){
        super();
        this.self = self;
        this.message = message;
        this.username = username;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        this.formattedDate = simpleDateFormat.format(message.getTime());
        initial();
    }
    private void initial(){
        //设置布局
        this.setLayout(new BorderLayout());
        //发送内容的时间
        JLabel dateLabel = new JLabel(formattedDate, SwingConstants.CENTER);
        //装有用户名和内容的头像的panel
        JPanel mainPanel = new JPanel(new FlowLayout());
        //头像
        JLabel headImage = new JLabel();
        JLabel username = new JLabel(this.username);
        username.setFont(ThisFont.MIDDLE_FONT);
        username.setForeground(MaterialColors.COSMO_BLACK);
        JTextArea content = new JTextArea(this.message.getText());
        content.setEditable(false);
        content.setFont(ThisFont.MIDDLE_BOLD_FONT);
        content.setBackground(MaterialColors.WHITE);
        content.setBorder(MaterialBorder.FOCUSED_LINE_BORDER);
        VFlowLayout vFlowLayout = new VFlowLayout();
        vFlowLayout.setVgap(0);
        vFlowLayout.setHgap(0);
        //根据是不是自己的消息选择不同的装填顺序
        JPanel panel = new JPanel(vFlowLayout);
        if (self){
            panel.add(username, JPanel.RIGHT_ALIGNMENT);
            panel.add(content, JPanel.RIGHT_ALIGNMENT);
            mainPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
            username.setHorizontalAlignment(SwingConstants.RIGHT);
            mainPanel.add(panel);
            mainPanel.add(headImage);
        } else {
            panel.add(username, JPanel.LEFT_ALIGNMENT);
            panel.add(content, JPanel.LEFT_ALIGNMENT);
            mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            username.setHorizontalAlignment(SwingConstants.LEFT);
            mainPanel.add(headImage);
            mainPanel.add(panel);
        }
        if (showDate){
            this.add(dateLabel, BorderLayout.NORTH);
        }
        this.add(mainPanel, BorderLayout.CENTER);
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                ImageIcon imageIcon;
                //一级缓存填充头像
                if (headImages.containsKey(message.getSender())){
                    imageIcon = headImages.get(message.getSender());
                } else {
                    imageIcon = Controller.USER_CONTROL.getHeadImage(message.getSender(),60);
                    headImages.put(message.getSender(), imageIcon);
                }
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        headImage.setIcon(imageIcon);
                    }
                });
            }
        });
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                String name;
                if (self){
                    name = UserState.getUsername();
                } else if (names.containsKey(message.getSender())){
                    name = names.get(message.getSender());
                } else {
                    ResponseEntity responseEntity = Controller.USER_CONTROL.getOtherUserInfo(message.getSender());
                    if (responseEntity.getCode() == 0) {
                        User user = JSONObject.parseObject(responseEntity.getData(), User.class);
                        names.put(message.getSender(), user.getUserName());
                        name = user.getUserName();
                    } else {
                        name = UserState.getUsername();
                    }
                }
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        username.setText(name);
                    }
                });
            }
        });
    }
}
